<template>
  <div class="device-form">
    <div class="e-nav-bar">
      <div>
        <van-icon class="e-nav-bar__back" name="arrow-left" size="24" @click="back" />
      </div>
      <div class="e-nav-bar__title e-flex-y-center e-flex-between">
        <div class="e-f-24 e-bold ell">{{!isAdd&&from!='VerifyFail'?'修改':'添加'}}{{typeObj.deviceCategoryName}}</div>
      </div>
    </div>
    <div style="height:90px;"></div>
    <div class="e-pl-10 e-pr-10">
      <!-- 当前单位 -->
      <div class="e-flex-y-center e-flex-between e-form-item">
        <div>
          <span class="e-color-red">*</span>
          <span class="e-bold e-f-16">当前单位</span>
        </div>
        <div class="e-flex-y-center e-flex-grow e-flex-end e-ml-10" @click="openUnit">
          <div class="e-color-333 e-f-14" :class="orgName?'e-color-333':'e-color-holder'">{{orgName||'请选择'}}</div>
          <van-icon v-if="userInfo.isMuilUnitUser" class="e-ml-5" name="arrow" />
        </div>
      </div>
      <!-- 系统类型 -->
      <div v-if="typeObj.pid==30" class="e-flex-y-center e-flex-between e-form-item">
        <div>
          <span class="e-color-red">*</span>
          <span class="e-bold e-f-16">系统类型</span>
        </div>
        <div class="e-flex-y-center e-flex-grow e-flex-end" @click="openSysType">
          <div class="e-f-14" :class="fireSystemTypeName?'e-color-333':'e-color-holder'">{{fireSystemTypeName||'请选择'}}</div>
          <van-icon class="e-ml-5" name="arrow" />
        </div>
      </div>
      <!-- 动态属性 -->
      <div v-for="n in attrList" :key="n.id">
        <div v-if="n.hide!==1" class="e-flex-y-center e-flex-between e-form-item">
          <div>
            <span v-if="n.required!==false" class="e-color-red">*</span>
            <span class="e-bold e-f-16">{{n.aliasName}}{{n.unit?'('+n.unit+')':''}}</span>
          </div>
          <div class="e-flex-y-center e-flex-grow">
            <van-field v-model="form[n.code]" :type="n.type||'text'" :placeholder="'请输入'+n.aliasName" clearable />
          </div>
          <van-icon v-if="n.code==deviceNoProp" class="e-ml-5" name="scan" size="24" @click="scan" />
        </div>
      </div>
      <!-- 物联设备名称 -->
      <div class="e-flex-y-center e-flex-between e-form-item">
        <div style="width:120px;">
          <span class="e-color-red">*</span>
          <span class="e-bold e-f-16">{{isTD?'':'物联'}}设备名称</span>
        </div>
        <div class="e-flex-grow e-ml-10">
          <van-field v-model="form.name" placeholder="请输入" clearable />
        </div>
      </div>
      <template v-if="!isTD">
        <!-- 复位方式 -->
        <div class="e-flex-y-center e-flex-between e-form-item">
          <div>
            <span class="e-color-red">*</span>
            <span class="e-bold e-f-16">复位方式</span>
          </div>
          <div class="e-flex-y-center e-flex-grow e-flex-end" @click="openReset">
            <div class="e-f-14 e-color-333">{{form.resetMode==1?'处理后复位':'自复位'}}</div>
            <van-icon class="e-ml-5" name="arrow" />
          </div>
        </div>

        <!-- 消防建筑结构 -->
        <div class="e-flex-y-center e-flex-between e-form-item">
          <div>
            <span class="e-color-red">*</span>
            <span class="e-bold e-f-16">消防建筑结构</span>
          </div>
          <div class="e-flex-y-center e-flex-1 e-flex-end e-ml-10" @click="form.organizationId?showfbsIdPicker = true:$toast('请先选择单位')">
            <div class="e-f-14" :class="orgName?'e-color-333':'e-color-holder'">{{buildName||'请选择'}}</div>
            <van-icon class="e-ml-5" name="arrow" />
          </div>
        </div>
        <!-- 具体位置 -->
        <div class="e-flex-y-center e-flex-between e-form-item">
          <div>
            <span class="e-color-red">*</span>
            <span class="e-bold e-f-16">具体位置</span>
          </div>
          <div class="e-flex-grow e-ml-10">
            <van-field v-model="form.location" placeholder="请输入" clearable />
          </div>
        </div>
        <!-- 关联视频 -->
        <div class="e-flex-y-center e-flex-between e-form-item">
          <div>
            <span class="e-bold e-f-16">关联视频</span>
          </div>
          <div class="e-flex-y-center e-flex-1 e-flex-end e-ml-10" @click="form.organizationId?videoPopup=true:$toast('请先选择单位')">
            <div class="e-f-14 text-right" :class="orgName?'e-color-333':'e-color-holder'">{{videoName||'请选择'}}</div>
            <van-icon class="e-ml-5" name="arrow" />
          </div>
        </div>
      </template>
      <template v-else>
        <div class="e-flex-y-center e-flex-between e-form-item">
          <div>
            <span class="e-color-red">*</span>
            <span class="e-bold e-f-16">报警主机</span>
          </div>
          <div class="e-flex-y-center e-flex-grow e-flex-end" @click="openHost">
            <div class="e-f-14" :class="hostName?'e-color-333':'e-color-holder'">{{hostName||'请选择'}}</div>
            <van-icon class="e-ml-5" name="arrow" />
          </div>
        </div>
      </template>
    </div>
    <div style="height:100px;"></div>
    <div class="e-fixed-b e-bg-white e-flex-y-center e-flex-between e-p-15">
      <van-button v-if="isAdd||from=='VerifyFail'" class="e-flex-grow van-button--theme" :disabled="loading" size="large" @click="save(1)">保存并验证</van-button>
      <van-button
        v-if="isAdd||from=='VerifyFail'"
        class="e-ml-10 e-flex-grow"
        type="default"
        :disabled="loading"
        size="large"
        @click="save(2)"
      >保存并继续添加</van-button>
      <van-button v-if="!isAdd&&from!='VerifyFail'" class="e-flex-grow van-button--theme" :disabled="loading" size="large" @click="save(2)">保存</van-button>
    </div>

    <!-- 选择单位 -->
    <unit-picker v-if="userInfo.isMuilUnitUser" ref="UnitPicker" :showButton="false" :currentOrgprops="currentOrgprops" @change="onUnitChange"></unit-picker>

    <!-- 复位方式 -->
    <van-popup v-model="resetPopup" position="bottom" :style="{ height: '40%' }">
      <van-picker show-toolbar :columns="resetColumns" @confirm="resetChange" @cancel="resetPopup=false" />
    </van-popup>

    <!-- 系统类型 -->
    <van-popup v-model="sysTypePopup" position="bottom" :style="{ height: '50%' }">
      <van-picker
        show-toolbar
        :columns="sysTypeColumns"
        value-key="name"
        :default-index="defaultSysTypeIndex"
        :visible-item-count="5"
        @confirm="sysTypeChange"
        @cancel="sysTypePopup=false"
      />
    </van-popup>

    <!-- 报警主机 -->
    <van-popup v-model="hostPopup" position="bottom" :style="{ height: '50%' }">
      <van-picker
        show-toolbar
        :columns="hostOptions"
        value-key="dictValue"
        :default-index="defaultHostIndex"
        :visible-item-count="5"
        @confirm="hostChange"
        @cancel="hostPopup=false"
      />
    </van-popup>

    <!-- 消防建筑结构 -->
    <van-popup v-model="showfbsIdPicker" round position="bottom">
      <van-cascader
        :options="options_fbsId"
        active-color="#2471CA"
        :field-names="fieldNames"
        :closeable="false"
        @close="showfbsIdPicker = false"
        @change="buildChange"
        @finish="showfbsIdPicker = false"
      >
        <div slot="title" class="e-flex-y-center">
          <div class="e-flex-grow">选择建筑物</div>
          <div class="e-color-primary e-p-5" @click="showfbsIdPicker=false">确认</div>
        </div>
      </van-cascader>
    </van-popup>

    <!-- 选择视频 -->
    <choose-video ref="chooseVideo" v-show="videoPopup" :orgIds="form.organizationId" @change="videoChange" @close="videoPopup=false" />

    <van-dialog
      v-model="showConfirm"
      show-cancel-button
      cancelButtonText="修改设备信息"
      cancelButtonColor="#999"
      :show-confirm-button="!isTD"
      confirmButtonText="查看设备"
      confirmButtonColor="#2471CA"
      @confirm="goDetail"
      @cancel="goEdit"
    >
      <div slot="title" class="e-flex-x-center e-relative e-bold e-pb-20 e-pt-20">
        该设备已存在！
        <div class="e-p-5" style="position:absolute;top:-20px;right:5px;" @click="showConfirm=false">
          <van-icon name="close" size="20" />
        </div>
      </div>
    </van-dialog>

    <van-overlay class="e-flex-xy-center" :show="loading" z-index="9" style="background: none;">
      <van-loading size="40px" color="#333" />
    </van-overlay>
  </div>
</template>

<style lang="scss">
.device-form {
  .van-cascader__title {
    flex: 1;
  }
}
</style>

<script>
import Schema from 'async-validator'
import { mapState } from 'vuex'
import ChooseVideo from './ChooseVideo.vue'
import UnitPicker from '@/components/UnitPicker'
import {
  saveUpSmoke,
  getDeviceCategoryInfo,
  getFcfDetailInfo,
  checkDeviceIdInfo,
  insertUpCommunicate,
  getUitbDetailInfo,
} from '@/api/device'
import { getOrgFbsTree, getDict } from '@/api/common'
import { shortNameMap } from '@/config/dict'

let deviceNoName = 'IMEI码'
let rules = {}
const deviceNoRule = {
  required: true,
  asyncValidator: (rule, value) => {
    return new Promise((resolve, reject) => {
      if (value && value.toString().length == 15) {
        resolve()
      } else {
        reject('请输入15位' + deviceNoName)
      }
    })
  },
}
const deviceNoRuleNumber = {
  required: true,
  asyncValidator: (rule, value) => {
    return new Promise((resolve, reject) => {
      if (value && /^\d{15}$/.test(value)) {
        resolve()
      } else {
        reject('请输入15位数字' + deviceNoName)
      }
    })
  },
}
const deviceNoRuleUT = {
  required: true,
  asyncValidator: (rule, value) => {
    return new Promise((resolve, reject) => {
      if (
        value &&
        /^\d{5}$/.test(value) &&
        Number(value) >= 10000 &&
        Number(value) <= 60000
      ) {
        resolve()
      } else {
        reject('用传设备编码5位数字，不大于60000')
      }
    })
  },
}

const deviceNoRuleMap = {
  71: {
    required: true,
    asyncValidator: (rule, value) => {
      return new Promise((resolve, reject) => {
        if (!value || value.toString().length != 14) {
          reject('请输入14位设备编码')
        } else {
          resolve()
        }
      })
    },
  },
  112: deviceNoRuleUT,
  113: deviceNoRuleUT,
}

const deviceNoPropMap = {
  71: 'systemaddr',
  111: 'serverId',
  112: 'serverId',
  113: 'serverId',
}

export default {
  components: { UnitPicker, ChooseVideo },

  data() {
    return {
      isAdd: true,
      from: '',
      typeObj: {
        deviceCategoryName: '',
      },
      form: {
        organizationId: '',
        deviceId: '',
        serverId: '',
        systemaddr: '',
        resetMode: '0',
        name: '',
        location: '',
        relateVideos: '',
      },
      isTop: 1,
      parentId: 0,
      resetColumns: [
        { text: '自复位', value: 0 },
        { text: '处理后复位', value: 1 },
      ],
      orgName: '',
      resetPopup: false,
      videoName: '',
      videoPopup: false,

      // 建筑物
      options_fbsId: [],
      fieldNames: {
        text: 'text',
        value: 'id',
        children: 'nodes',
      },
      showfbsIdPicker: false,
      fbsIdValue: '', //所属建筑物 名称
      currentOrgprops: {},
      buildName: '',

      attrList: [],
      loading: false,
      showConfirm: false,
      // 是否传输装置
      isTD: false,
      // 是否用传
      isUT: false,
      // 是否DTU
      isDTU: false,

      fireSystemTypeName: '',
      sysTypePopup: false,
      sysTypeColumns: [],
      defaultSysTypeIndex: 0,

      hostName: '',
      hostPopup: false,
      defaultHostIndex: 0,
      hostOptions: [],
    }
  },

  computed: {
    ...mapState(['userInfo']),
    deviceNoProp() {
      return deviceNoPropMap[this.typeObj.id] || 'deviceId'
    },
    deviceNoField() {
      return this.attrList.find((n) => {
        return n.code == this.deviceNoProp
      })
    },
  },

  watch: {
    'form.organizationId'() {
      if (!this.ignoreOrgChange) {
        this.clearVideo()
        this.clearBuild()
      }
      this.getOrgFbsTree()
    },
    'form.deviceId'(val, oldVal) {
      if (!this.ignoreDeviceChange && val.toString() !== oldVal.toString()) {
        this.setDeviceName(val)
        this.changeServerId(val)
      }
    },
    'form.serverId'(val, oldVal) {
      if (!this.ignoreDeviceChange && val.toString() !== oldVal.toString()) {
        this.setDeviceName(val)
        this.changeServerId(val)
      }
    },
    'form.systemaddr'(val, oldVal) {
      if (!this.ignoreDeviceChange && val.toString() !== oldVal.toString()) {
        this.setDeviceName(val)
      }
    },
    orgName(val) {
      if (!this.ignoreDeviceChange && this.isTD) {
        this.setDeviceName(this.form.serverId)
      }
    },
    videoPopup(val) {
      if (val) {
        myVue.showChooseVideo = () => {
          this.videoPopup = false
        }
      } else {
        myVue.showChooseVideo = null
      }
    },
  },

  created() {
    let { code, typeObj = {}, data = {}, from } = this.$route.params
    this.from = from
    if (code) {
      this.isAdd = true
      // 新增
      this.typeObj = typeObj
      this.setIsTD()
      this.$nextTick(() => {
        this.form[this.deviceNoProp] = code
        this.setDeviceName(code)
        this.setDefaultOrg()
        this.getDeviceCategoryInfo()
      })
    } else {
      if (from == 'VerifyFail') {
        this.typeObj = typeObj
      }
      // 编辑
      if (data.businessType == 1) {
        this.isTD = false
        this.getDetail(data)
      } else if (data.businessType == 2) {
        this.isTD = true
        this.getDTUDetail(data)
      }
    }
    window.getQode = (code) => {
      this.checkDeviceIdInfo(code)
    }
  },

  mounted() {},

  methods: {
    setIsTD() {
      this.isTD = this.typeObj.pid == 110
      this.isUT = this.typeObj.id == 112 || this.typeObj.id == 113
      this.isDTU = this.typeObj.id == 111
    },
    changeServerId(val) {
      if (this.isDTU && val.toString().length > 5) {
        console.log('DTU:changeServerId')
        let one = this.hostOptions.find((n) => {
          return n.dictKey == val.substr(val.length - 6, 3)
        })
        if (one) {
          this.form.protocolMark = one.dictKey
          this.hostName = one.dictValue
        } else {
          this.form.protocolMark = ''
          this.hostName = ''
        }
      }
    },
    openHost() {
      this.defaultHostIndex =
        this.hostOptions.findIndex((n) => {
          return n.dictKey == this.form.protocolMark
        }) || 0
      this.hostPopup = true
    },
    hostChange(val) {
      this.hostPopup = false
      this.form.protocolMark = val.dictKey
      this.hostName = val.dictValue
    },
    getDicts() {
      if (this.isTD) {
        getDict({ code: this.isUT ? 116 : 115 }).then((res) => {
          this.hostOptions = res.data.dictValueObj
          if (this.isAdd) {
            if (this.isUT) {
              if (this.hostOptions.length == 1) {
                this.form.protocolMark = this.hostOptions[0].dictKey
                this.hostName = this.hostOptions[0].dictValue
              }
            } else {
              this.changeServerId(this.form.serverId)
            }
          }
        })
      }
    },
    openSysType() {
      this.defaultSysTypeIndex =
        this.sysTypeColumns.findIndex((n) => {
          return n.id == this.form.fireSystemTypeId
        }) || 0
      this.sysTypePopup = true
    },
    sysTypeChange(val, index) {
      this.sysTypePopup = false
      this.form.fireSystemTypeId = val.id
      this.fireSystemTypeName = val.name
      this.setAttrList(this.valueArr[index], true)
      this.setFcFacilitiesCategory(this.valueArr[index])
    },
    getDeviceCategoryInfo(callback) {
      getDeviceCategoryInfo({ id: this.typeObj.id }).then(({ data }) => {
        this.typeObj.pid = data.deviceType
        this.setIsTD()
        this.getDicts()
        this.typeObj.deviceCategoryName = data.deviceCategoryName
        this.form.protocolType = data.protocolType
        if (data.defaultValue) {
          this.valueArr = JSON.parse(data.defaultValue)
          this.sysTypeColumns = this.valueArr.map((n) => {
            return n.fireSystem
          })
          let sysTypeIndex = 0
          if (!this.isAdd) {
            sysTypeIndex =
              this.sysTypeColumns.findIndex((n) => {
                return n.id == this.form.fireSystemTypeId
              }) || 0
          }
          let valueObj = this.valueArr[sysTypeIndex] || {}
          this.setAttrList(valueObj)
          callback && callback(valueObj.property || [])
          if (this.isAdd) {
            this.setFcFacilitiesCategory(this.valueArr[0])
          }
        } else {
          this.setRules()
        }
      })
    },
    setAttrList(valueObj, isChangeSys) {
      this.attrList = valueObj.property || []
      this.$nextTick(() => {
        this.setRules()
        this.attrList.forEach((n) => {
          if (n.code !== this.deviceNoProp) {
            if (this.isAdd || isChangeSys) {
              this.$set(this.form, n.code, n.defaultVal)
            }
          }
          if (n.code != this.deviceNoProp) {
            if (n.required !== false) {
              rules[n.code] = {
                required: true,
                message: '请填写' + n.aliasName,
              }
            }
          } else {
            deviceNoName = n.aliasName
          }
        })
      })
    },
    setFcFacilitiesCategory(valueObj) {
      if (valueObj.fireSystem) {
        this.form.fireSystemTypeId = valueObj.fireSystem.id
        this.fireSystemTypeName = valueObj.fireSystem.name
        this.form.fcFacilitiesCategoryId =
          valueObj.fireSystem.fcFacilitiesCategoryId
        this.form.producerId = valueObj.fireSystem.producerId
      }
    },
    // 物联设备详情
    getDetail(obj) {
      this.isAdd = false
      this.ignoreOrgChange = true
      this.ignoreDeviceChange = true
      this.loading = true
      getFcfDetailInfo({ recordId: obj.recordId })
        .then(({ data }) => {
          this.form.id = data.id
          this.form.organizationId = data.orgId
          this.orgName = data.orgName
          this.form.fireSystemTypeId = data.fireSystemTypeId
          this.fireSystemTypeName = data.fireSystemTypeName
          this.form.fcFacilitiesCategoryId = data.fcFacilitiesCategoryId
          this.form.fireBuildingStructureId = data.fireBuildingStructureId
          this.buildName = data.fbsName
          this.isTop = data.isTop
          this.parentId = data.parentId
          if (data.relateVideo && data.relateVideo.length > 0) {
            this.form.relateVideos = data.relateVideo
              .map((n) => {
                return n.videoId
              })
              .join(',')
            this.videoName = data.relateVideo
              .map((n) => {
                return n.videoName
              })
              .join(',')
          }
          this.typeObj.id = data.deviceCategoryId.toString()
          this.getDeviceCategoryInfo((attrList) => {
            attrList.forEach((n) => {
              if (n.attribute && n.attribute[0]) {
                this.$set(this.form, n.code, this.form[n.attribute[0].code])
              }
            })
          })
          this.form.name = data.name
          this.form.resetMode = data.resetMode
          this.form.location = data.location
          this.form.producerId = data.producerId
          data.dtoList.forEach((n) => {
            n.properties &&
              n.properties.forEach((p) => {
                this.$set(this.form, p.code, p.val)
              })
            n.nodes &&
              n.nodes.forEach((node) => {
                node.properties &&
                  node.properties.forEach((p) => {
                    this.$set(this.form, p.code, p.val)
                  })
              })
          })
          this.$nextTick(() => {
            this.ignoreOrgChange = false
            this.ignoreDeviceChange = false
          })
          this.loading = false
        })
        .catch((e) => {
          console.log('getFcfDetailInfo', e)
          this.loading = false
        })
    },
    // DTU详情
    getDTUDetail(obj) {
      this.isAdd = false
      this.ignoreOrgChange = true
      this.ignoreDeviceChange = true
      this.loading = true
      getUitbDetailInfo({ recordId: obj.recordId })
        .then(({ data }) => {
          this.form.id = data.id
          this.form.organizationId = data.orgId
          this.orgName = data.orgName
          this.form.fireSystemTypeId = data.fireSystemTypeId
          this.typeObj.id = data.deviceCategoryId.toString()
          this.getDeviceCategoryInfo()
          this.form.name = data.name
          this.form.serverId = data.serverId
          this.form.model = data.model
          this.form.protocolMark = data.protocolMark
          this.hostName = data.protocolMarkName
          this.serialNo = data.serialNo
          this.$nextTick(() => {
            this.ignoreOrgChange = false
            this.ignoreDeviceChange = false
          })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    setDeviceName(val) {
      if (this.typeObj.pid) {
        val = val.toString()
        let suffix = val.toString().substr(val.length - 4, val.length - 1)
        if (this.isTD) {
          if (this.isUT) {
            suffix = val
          }
          this.form.name = this.orgName + shortNameMap[this.typeObj.id] + suffix
        } else {
          this.form.name = shortNameMap[this.typeObj.id] + suffix
        }
      }
    },
    checkDeviceIdInfo(code, isSave) {
      checkDeviceIdInfo({ deviceNo: code, deviceType: this.typeObj.pid }).then(
        ({ data }) => {
          if (data) {
            this.showRepeatTip(data)
          } else {
            if (isSave) {
              this.requestSave()
            } else {
              this.form[this.deviceNoProp] = code
            }
          }
        }
      )
    },
    goDetail() {
      window.top.goDeviceDetail({
        fcFacilitiesId: this.repeatBizId,
      })
    },
    goEdit() {
      this.clearFormData()
      if (this.isTD) {
        this.getDTUDetail({
          recordId: this.repeatBizId,
        })
      } else {
        this.getDetail({
          recordId: this.repeatBizId,
        })
      }
    },
    showRepeatTip(id) {
      this.repeatBizId = id
      this.showConfirm = true
    },
    requestSave() {
      if (this.loading) return
      let params
      let api
      if (this.isTD) {
        api = insertUpCommunicate
        params = {
          id: this.form.id,
          deviceType: this.typeObj.pid,
          deviceCategoryId: this.typeObj.id,
          name: this.form.name,
          organizationId: this.form.organizationId,
          isDevice: this.typeObj.id == 111 ? 0 : 1,
          account: this.userInfo.accountName,
          protocolMark: this.form.protocolMark || '',
        }
        if (this.serialNo) {
          params.serialNo = this.serialNo
        }
        this.attrList.forEach((n) => {
          params[n.code] = this.form[n.code]
        })
      } else {
        api = saveUpSmoke
        let propMap = {}
        this.attrList.forEach((n) => {
          if (n.attribute) {
            n.attribute.forEach((m) => {
              if (!propMap[m.fcFacilitiesCategoryId]) {
                propMap[m.fcFacilitiesCategoryId] = []
              }
              propMap[m.fcFacilitiesCategoryId].push({
                fcFacilitiesPropertyId: m.fcFacilitiesPropertyId,
                val: this.form[n.code],
                code: m.code,
              })
            })
          }
          if (!propMap[n.fcFacilitiesCategoryId]) {
            propMap[n.fcFacilitiesCategoryId] = []
          }
          propMap[n.fcFacilitiesCategoryId].push({
            fcFacilitiesPropertyId: n.fcFacilitiesPropertyId,
            val: this.form[n.code],
            code: n.code,
          })
        })
        // console.log('form',JSON.stringify(this.form))
        let propertyVal = Object.keys(propMap).map((n) => {
          return {
            fcFacilitiesCategoryId: n,
            properties: propMap[n],
          }
        })
        // console.log('propertyVal', JSON.stringify(propertyVal))
        params = {
          account: this.userInfo.accountName,
          id: this.form.id || 0,
          deviceType: this.typeObj.pid,
          deviceCategoryId: this.typeObj.id || 114,
          fcFacilitiesCategoryId: this.form.fcFacilitiesCategoryId,
          fireSystemTypeId: this.form.fireSystemTypeId,
          isTop: this.isTop,
          name: this.form.name,
          organizationId: this.form.organizationId,
          parentId: this.parentId,
          protocolType: this.form.protocolType,
          relateFcfIds: this.form.relateFcfIds,
          relateVideos: this.form.relateVideos,
          resetMode: this.form.resetMode,
          fireBuildingStructureId: this.form.fireBuildingStructureId,
          location: this.form.location,
          producerId: this.form.producerId,
          propertyVal: JSON.stringify(propertyVal),
        }
      }
      this.loading = true
      api(params)
        .then(({ status, info, data }) => {
          if (status == 200) {
            this.$toast('保存成功')
            if (this.saveType == 2) {
              this.goStart()
            } else {
              this.$router.replace({
                name: 'Verifying',
                params: {
                  id: data,
                  deviceNo: this.form[this.deviceNoProp],
                  deviceName: this.form.name,
                  typeObj: this.typeObj,
                },
              })
            }
          } else if (status == 400001) {
            this.showRepeatTip(data)
          } else {
            this.$toast(info)
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    validate() {
      new Schema(rules).validate(this.form, { first: true }, (errors) => {
        if (errors) {
          return this.$toast(errors[0].message)
        }
        if (this.isAdd) {
          this.checkDeviceIdInfo(this.form[this.deviceNoProp], true)
        } else {
          this.requestSave()
        }
      })
    },
    save(val) {
      this.saveType = val
      this.validate()
    },
    getOrgFbsTree() {
      if (!this.form.organizationId) return
      getOrgFbsTree({
        orgIds: this.form.organizationId,
        buildId: 0,
      }).then((res) => {
        this.options_fbsId = res.data
      })
    },
    openUnit() {
      if (!this.userInfo.isMuilUnitUser) return
      this.$refs.UnitPicker.active = true
    },
    onUnitChange(val) {
      this.form.organizationId = val.organizationId
      this.orgName = val.shortName
      localStorage.setItem('ilink_addDeviceDefaultOrgName', val.shortName)
      localStorage.setItem('ilink_addDeviceDefaultOrgId', val.organizationId)
    },
    resetChange(val) {
      this.form.resetMode = val.value
      this.resetPopup = false
    },
    openReset() {
      this.resetPopup = true
    },
    videoChange(val) {
      this.form.relateVideos = val.value
      this.videoName = val.name
    },
    clearVideo() {
      this.form.relateVideos = ''
      this.videoName = ''
    },
    buildChange({ selectedOptions }) {
      this.buildName = selectedOptions.map((option) => option.text).join('>')
      this.form.fireBuildingStructureId =
        selectedOptions[selectedOptions.length - 1].id
    },
    clearBuild() {
      this.form.fireBuildingStructureId = ''
      this.buildName = ''
    },
    goForm(code) {
      this.$router.replace({
        name: 'DeviceForm',
        params: {
          code,
          type: this.type,
        },
      })
    },
    goStart() {
      this.$router.replace({
        name: 'AddDevice',
      })
    },
    back() {
      if (this.$route.params.from == 'VerifyFail') {
        this.$router.replace({
          name: 'VerifyFail',
          params: this.$route.params,
        })
      } else {
        this.$router.go(-1)
      }
    },
    resetForm() {
      this.clearFormData()
      this.setDefaultOrg()
    },
    setDefaultOrg() {
      if (this.isAdd) {
        if (!this.userInfo.isMuilUnitUser) {
          if (this.userInfo.org) {
            this.orgName = this.userInfo.org.name
            this.form.organizationId = this.userInfo.org.id
          }
        } else {
          this.orgName =
            localStorage.getItem('ilink_addDeviceDefaultOrgName') || ''
          this.form.organizationId =
            localStorage.getItem('ilink_addDeviceDefaultOrgId') || ''
        }
      }
    },
    clearFormData() {
      Object.keys(this.form).forEach((n) => {
        this.form[n] = ''
      })
      this.form.resetMode = '0'
      this.videoName = ''
      this.buildName = ''
      this.orgName = ''
      this.fireSystemTypeName = ''
      this.$refs.chooseVideo.videoIds = []
    },
    scan() {
      this.$native.scanQrCode()
    },
    setRules() {
      rules = {
        organizationId: { required: true, message: '请选择单位' },
      }
      if (this.deviceNoField) {
        rules[this.deviceNoProp] =
          deviceNoRuleMap[this.typeObj.id] ||
          (this.deviceNoField.type == 'number'
            ? deviceNoRuleNumber
            : deviceNoRule)
      }
      rules.name = {
        asyncValidator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if (!value) {
              reject('请填写设备名称')
            } else if (value.length > 15) {
              reject('设备名称不能超过15位字符')
            } else {
              resolve()
            }
          })
        },
      }
      if (!this.isTD) {
        Object.assign(rules, {
          fireBuildingStructureId: {
            required: true,
            message: '请选择消防建筑结构',
          },
          location: {
            asyncValidator: (rule, value) => {
              return new Promise((resolve, reject) => {
                if (!value) {
                  reject('请填写具体位置')
                } else if (value.length > 50) {
                  reject('具体位置不能超过50位字符')
                } else {
                  resolve()
                }
              })
            },
          },
        })
      }
      if (this.typeObj.pid == 30) {
        rules.fireSystemTypeId = { required: true, message: '请选择系统类型' }
      }
    },
  },
}
</script>